import 'dart:collection';
import 'package:dio/dio.dart';
import 'package:pax_info_app/model/sys_info.dart';
import 'package:flutter/cupertino.dart';
import '../address.dart';
import '../http_manager.dart';

/**
 * Token拦截器
 * Created by zongjian
 * Date: 2019-06-18
 */
class TokenInterceptors extends InterceptorsWrapper {

  String? _token;

  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    //授权码
//    if (options.path.indexOf('/oauth/token') < 0) {
//
//    }
//    if (_token == null) {
//      var authorizationCode = await getAuthorization();
//      if (authorizationCode != null) {
//        _token = authorizationCode;
//      }
//    }
    var authorizationCode = await getAuthorization();
    options.headers["Authorization"] = authorizationCode;
    return handler.next(options);

  }


  @override
  onResponse(Response response, ResponseInterceptorHandler handler) async{
    try {
      var responseJson = response.data;
//      if (response.statusCode == 201 && responseJson["access_token"] != null) {
//        _token = responseJson["access_token"];
//        await LocalStorage.set(Config.ACCESS_TOKEN, _token);
//      }
      if (responseJson['code'] == 40001) {
        RequestOptions options = response.requestOptions;
        return getAccessTokenByRefreshToken(options, handler: handler, oriResponse: response);
      }
    } catch (e, s) {
      // CommonUtils.captureException(e, stackTrace: s);
      // if (e.response.statusCode == 40001) {
      //   RequestOptions options = e.response.request;
      //   return getAccessTokenByRefreshToken(options, handler: handler, oriResponse: response);
      // }
    }
    return handler.next(response);
  }

  @override
  onError(DioError err, handler) async {
    if (err.response != null && err.response!.statusCode == 40001) { /// 40001代表access_token过期
      RequestOptions options = err.response!.requestOptions;
      return getAccessTokenByRefreshToken(options);
    }
    return handler.next(err);
//    super.onError(err);
  }

  /// 通过 refresh_token 获取 access_token
  getAccessTokenByRefreshToken(options, {
    params,
    ResponseInterceptorHandler? handler,
    Response? oriResponse }) async {
    // if (SysInfo.instance.isLocked) return handler.next(oriResponse);
    // SysInfo.instance.isLocked = true;
    await SysInfo.instance.save();

    debugPrint('********  重新获取 access_token ${DateTime.now().millisecondsSinceEpoch}  *********');
    String? refreshToken = SysInfo.instance.refreshToken;
    debugPrint('refreshToken ==> $refreshToken');
    //重新发起一个请求获取数据

    try {
      final path = Address.addArgs(Address.kRefreshToken, [refreshToken]);
      var res = await httpManagerNoToken.request(path, HttpMethod.GET, noTip: true);
      // Response res = await httpManagerNoToken.request(Address.kRefreshToken + '&refreshToken=' + refreshToken);
      debugPrint('********  refreshToken ${res.data}  *********');
      if (res != null) {
        if (res.data['access_token'] != null) {
          // SysInfo.instance.isLocked = false;
          SysInfo.instance.accessToken = res.data["access_token"];
          SysInfo.instance.refreshToken = res.data["refresh_token"];
          await SysInfo.instance.save();
          options.headers["Authorization"] = SysInfo.instance.getToken();
          print('=== options: ${options.toString()}');

          Map<String, dynamic> headers = new HashMap();
          headers.addAll({
            'Authorization': SysInfo.instance.getToken()
          });
          Options option = new Options(
            headers: headers,
            method: options.method,

          );

          var resp = await httpManager.dio.request(
            options.path,
            options: option,
            data: options.data,
            queryParameters: options.queryParameters,
          );
          return handler!.next(resp);
        } else {
          // httpManager.dio.unlock(); //解锁
          // httpManager.dio.interceptors.requestLock.unlock();
          // httpManager.dio.interceptors.responseLock.unlock();
          // SysInfo.instance.isLocked = false;
          await SysInfo.instance.save();
          reLogin();
          // eventBus.fire(ShowLoginEvent(true));
          // eventBus.fire(LogoutEvent(true));
          return handler!.next(oriResponse!);
        }
      } else {
        // httpManager.dio.unlock(); //解锁
        // httpManager.dio.interceptors.requestLock.unlock();
        // httpManager.dio.interceptors.responseLock.unlock();
        // SysInfo.instance.isLocked = false;
        await SysInfo.instance.save();
        reLogin();
        // eventBus.fire(ShowLoginEvent(true));
        // eventBus.fire(LogoutEvent(true));
        return handler!.next(oriResponse!);
      }
    } on DioError catch (e, s) {
      // httpManager.dio.unlock(); //解锁
      // httpManager.dio.interceptors.requestLock.unlock();
      // httpManager.dio.interceptors.responseLock.unlock();
      // SysInfo.instance.isLocked = false;
      await SysInfo.instance.save();
      print('重新获取 access_token 错误：$e');
      reLogin();
      // eventBus.fire(ShowLoginEvent(true));
      // eventBus.fire(LogoutEvent(true));
      // CommonUtils.captureException(e, stackTrace: s);
      return handler!.reject(e);
    }
    // finally {
    //   httpManager.dio.unlock(); //解锁
    //   httpManager.dio.interceptors.responseLock.unlock();
    //   httpManager.dio.interceptors.errorLock.unlock();
    // }
  }

  /// 重新登录
  reLogin() async {
    // return await AppRepository.login(
    //     username: SysInfo.instance.loginAccount,
    //     password: SysInfo.instance.password).then((v) async {
    //   await SysInfo.instance.parseUserInfo(v.data);
    // });
  }

  ///清除授权
  clearAuthorization() {
    this._token = null;
    SysInfo.instance.clearLogin();
  }

  ///获取授权token
  getAuthorization() async {
    String token = SysInfo.instance.getToken();
    print('token =====> $token');
    this._token = token;
    return token;
//     if (token == null) {
//       String basic = await LocalStorage.get(Config.USER_BASIC_CODE);
//       if (basic == null) {
//         //提示输入账号密码
//       } else {
//         //返回token
//         String username = await LocalStorage.get(Config.USER_NAME_KEY);
//         String password = await LocalStorage.get(Config.PW_KEY);
//         String accessToken = '';
//         Dio tokenDio = new Dio(); // 创建新Dio实例
//         String url = Address.getAuthorization('password') + '&username=' + username + '&password=' + CommonUtils.generateMd5(password);
// //        var res = await httpManager.fetchToken(Address.getAuthorization('password') + '&username=' + username + '&password=' + CommonUtils.generateMd5(password));
//         var res = await tokenDio.get(url); //请求refreshToken刷新的接口
//         print('aaa: $res');
//         if (res != null && res.data['access_token'] != null) {
//           await LocalStorage.set(Config.ACCESS_TOKEN, res.data["access_token"]);
//           await LocalStorage.set(Config.REFRESH_TOKEN, res.data["refresh_token"]);
//           accessToken = res.data['access_token'];
//         }
//         return accessToken;
//       }
//     } else {
//       this._token = token;
//       return token;
//     }
  }

}